<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="用户姓名" prop="nickName">
        <el-input v-model="queryParams.params.nickName" placeholder="请输入用户姓名" clearable/>
      </el-form-item>
      <el-form-item label="预约时间">
        <el-date-picker v-model="daterangeAppointTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="履行状态" prop="doStatus">
        <el-select v-model="queryParams.doStatus" placeholder="请选择履行状态" clearable>
          <el-option v-for="dict in dict.type.appoint_record_do_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.appoint_record_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <br>
      <el-form-item label="实训预约" prop="appointId">
        <el-select v-model="queryParams.appointId" @change="getAppointTimeList" placeholder="请选择实训预约" clearable style="width: 260px">
          <el-option v-for="item in appointList" :key="item.id" :value="item.id" :label="item.project">
            {{item.project}}
            <span style="float: right;font-size: 13px;color: #99a9bf;margin-left: 20px;">{{item.teacher}}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间段" prop="appointTimeId">
        <el-select v-model="queryParams.appointTimeId" placeholder="请选择预约时间段" :disabled="isEmptyArr(appointTimeList)" clearable style="width: auto;">
          <el-option v-for="item in appointTimeList" :key="item.id" :value="item.id" :label="item.name">
            {{item.name}}
            <span style="float: right;font-size: 13px;color: #99a9bf;margin-left: 20px;">{{item.startTime}}~{{item.endTime}}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-user" size="mini" @click="handleNotAppoint" v-hasPermi="['pv:appoint_record:query']">查看未报名的学员</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['pv:appoint_record:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['pv:appoint_record:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['pv:appoint_record:export']">导出</el-button>
      </el-col>-->
<!--      <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['pv:appoint_record:edit']">修改</el-button>-->

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appoint_recordList">
      <el-table-column label="学生" align="center" prop="student.nickName" width="100"/>
      <el-table-column label="项目" align="center" prop="appoint.project"/>
      <el-table-column label="预约时间" align="center" prop="appointDate" width="110">
        <template slot-scope="scope">
          <el-tag size="mini" effect="plain">{{scope.row.appointDate}}</el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="是否补约" align="center" prop="reservedOne"/>-->

      <el-table-column label="是否补约" align="center" prop="reservedOne" width="110">
        <template slot-scope="scope">
          <el-tag size="mini" effect="plain" v-if="scope.row.reservedOne">{{scope.row.reservedOne}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="学生手机" align="center" prop="student.phonenumber" width="110"/>
      <el-table-column label="实训项目" align="center" prop="appoint.trainingProgramName"/>
      <el-table-column label="预约时段" align="center" prop="appointTimeId">
        <template slot-scope="scope">
          <el-tag type="danger" size="mini">{{scope.row.appointTime.name}}</el-tag>
          <el-tag size="mini" effect="plain">
            {{scope.row.appointTime.startTime}} ~ {{scope.row.appointTime.endTime}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="履行" align="center" prop="doStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.appoint_record_do_status" :value="scope.row.doStatus"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="评分表" align="center" class-name="small-padding fixed-width" width="100">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button size="small" type="primary" icon="el-icon-edit" @click="openScore(scope.row)" plain>评分表</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.appoint_record_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown v-if="scope.row.status == '0'" size="mini" @command="(command) => checkStatusCommand(command, scope.row)" v-hasPermi="['pv:appoint_record:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">核准</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1" icon="el-icon-circle-check" v-hasPermi="['pv:appoint_record:edit']">同意</el-dropdown-item>
              <el-dropdown-item command="2" icon="el-icon-circle-close" v-hasPermi="['pv:appoint_record:edit']">不同意</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleSupplementaryExamination(scope.row)" v-hasPermi="['pv:appoint_record:edit']">补考预约</el-button>
          <el-button v-if="scope.row.status == '1' && scope.row.doStatus != '1'" size="mini" type="text" icon="el-icon-s-promotion" @click="checkDoStatusCommand(scope.row)" v-hasPermi="['pv:appoint_record:edit']">已履行</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['pv:appoint_record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>


    <!-- 添加或修改实训预约对话框 -->
    <el-dialog :title="title" :visible.sync="openSupplementaryExamination" width="800px" append-to-body>
      <el-form ref="form" :model="formAppointTime" :rules="rules" label-width="120px">

        <el-form-item label="预约日期" prop="appointDate">
          <el-alert v-if="appoint.beginDate && appoint.endDate && appoint.beginDate === appoint.endDate"
                    title="只能选择这一天" type="info" :closable="false" show-icon style="margin-bottom: 10px;"/>
          <el-date-picker v-model="pvAppointRecord.appointDate" type="date" placeholder="选择日期"
            :picker-options="pickerOptions" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
            @change="handleDateChange" :disabled="!appoint.beginDate || !appoint.endDate"/>
        </el-form-item>

        <el-form-item label="上课时间">

          <el-table :data="pvAppointTimeList" ref="pvBookingTimeInfo" size="mini">

            <el-table-column width="60">
              <template slot-scope="scope">
                <el-radio v-model="pvAppointRecord.appointTimeId" :label="scope.row.id"
                  @change="handleRadioChange">&nbsp;
                </el-radio>
              </template>
            </el-table-column>

            <el-table-column label="可预约场次" prop="name" width="150">
              <template slot-scope="scope">
                {{ scope.row.name }}
              </template>
            </el-table-column>

            <el-table-column label="时间范围" prop="time" width="180">
              <template slot-scope="scope">
                {{ scope.row.time ? `${scope.row.time[0]} - ${scope.row.time[1]}` : '' }}
              </template>
            </el-table-column>

            <el-table-column label="剩余名额" prop="name" width="80" align="center" >
              <template slot-scope="scope">
                <el-tag type="primary">{{ scope.row.num }}</el-tag>
              </template>
            </el-table-column>

          </el-table>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updatePvAppointRecordForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>


    <!-- 添加或修改预约记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生编号" prop="stuId">
          <el-input v-model="form.stuId" placeholder="请输入学生编号"/>
        </el-form-item>
        <el-form-item label="预约编号" prop="appointId">
          <el-input v-model="form.appointId" placeholder="请输入预约编号"/>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointTime">
          <el-date-picker clearable v-model="form.appointTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择预约时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="时段编号" prop="bookingTime">
          <el-input v-model="form.bookingTime" placeholder="请输入时段编号"/>
        </el-form-item>
        <el-form-item label="履行状态" prop="doStatus">
          <el-radio-group v-model="form.doStatus">
            <el-radio v-for="dict in dict.type.appoint_record_do_status" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.appoint_record_status" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer title="未预约学员" :visible.sync="not_appoint.open" :modal="false">
      <el-form ref="form" label-width="80px">
        <el-form-item label="实训预约" prop="appointId">
          <el-select v-model="not_appoint.appointId" @change="getNotAppointList" placeholder="请选择实训预约" clearable>
            <el-option v-for="item in appointList" :key="item.id" :value="item.id" :label="item.project">
              {{item.project}}
              <span style="float: right;font-size: 9px;color: #99a9bf">{{item.teacher}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-table :data="not_appoint.userList" height="1000px" size="mini">
            <el-table-column label="学生姓名" align="center" prop="name"/>
            <el-table-column label="社区" align="center" prop="com">
              <template slot="header" slot-scope="scope">
                社区 <el-tag style="float: right">{{not_appoint.userList.length}}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 查看评分表对话框 -->
    <el-drawer :wrapperClosable="false" :title="score.title" :visible.sync="score.open" size="85%" append-to-body center destroy-on-close>
      <div slot="title">
        {{ score.title }} <br><span style="font-size: 10px;">按ESC可退出</span>
      </div>
      <div style="padding: 1rem;">
        教师：<el-tag type="success" effect="plain">{{score.teacher.nickName}}</el-tag>
        <el-tabs v-model="score.activeName">
          <el-tab-pane label="产妇" name="puerpera" :disabled="!checkPermi(['pv:stu_record:edit:pregnant'])"></el-tab-pane>
          <el-tab-pane label="新生儿" name="children" :disabled="!checkPermi(['pv:stu_record:edit:child'])"></el-tab-pane>
        </el-tabs>
        <div>
          <center>
            <el-table :data="score.model" style="width: 1027px" border :span-method="objectSpanMethod" size="mini" :header-cell-style="{ textAlign: 'center' }">
              <el-table-column>
                <template slot="header" slot-scope="scope">
                  <span style="font-size: 20px;font-family: 仿宋;">产褥期保健操作评分表（{{score.activeName === 'puerpera' ? '产妇' : '新生儿'}}）</span>
                  <el-button style="float: right;" size="mini" icon="el-icon-circle-check" type="success" @click="recordUpdate" v-hasPermi="['pv:stu_record:edit']" round>提交</el-button>
                </template>
                <el-table-column prop="project" align="center" label="项目"></el-table-column>
                <el-table-column prop="step" align="center" label="步骤"></el-table-column>
                <el-table-column prop="content" align="center" label="具体内容" width="500"></el-table-column>
                <el-table-column prop="value" align="center" label="分值"></el-table-column>
                <el-table-column label="得分" width="109">
                  <template slot-scope="scope">
                    <el-input-number v-if="isNotNull(score.scores[scope.$index])"  controls-position="right" @input="$forceUpdate()" style="width: 84px" :min="0" :max="scope.row.value" v-model="score.scores[scope.$index]"/>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
            <el-input style="width: 1027px;margin-top: 5px" type="textarea" :rows="6" placeholder="备注" v-model="score.comments"/>
          </center>
        </div>
      </div>

    </el-drawer>
  </div>
</template>

<script>
import {
  listAppoint_record,
  delAppoint_record,
  addAppoint_record,
  updateAppoint_record, get_not_appoint_list, getAppoint_record, getAppoint_record_time_list, updateAppoint_buyuerecord
} from '@/api/pv/appoint_record'
import {getRecord_by_class_user, updateStu_record} from '@/api/pv/stu_record'
import {listAppoint,getAppoint} from "@/api/pv/appoint";
import {arrSum, copyArr, isEmptyArr} from "@/utils/zzDouUtils/arrayUtil";
import {isEmptyStr, parseObj, toJsonStr} from "@/utils/zzDouUtils/ObjUtil";
import {readJson} from "@/api/file";
import {checkPermi} from "@/utils/permission";


export default {
  name: "Appoint_record",
  dicts: ['appoint_record_do_status', 'appoint_record_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约记录表格数据
      appoint_recordList: [],
      // 实训预约表格数据
      appointList: [],
      // 实训预约时间段数据
      appointTimeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 补约显示弹出层
      openSupplementaryExamination: false,
      // 状态时间范围
      daterangeAppointTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuId: null,
        appointId: null,
        appointDate: null,
        appointTimeId: null,
        doStatus: null,
        status: null,
        params:{},
      },
      appointTimeId: null,
      pvAppointRecordId: null,
      // 表单参数
      form: {},
      pvAppointRecord: {},
      formAppointTime: {
        appointDate : null,
      },
      appoint: {},
      // 实训预约时间段列表（用于编辑）
      pvAppointTimeList: [],
      pickerOptions: {
        disabledDate: (time) => {
          if (!this.appoint.beginDate || !this.appoint.endDate) return true;

          const beginDate = new Date(this.appoint.beginDate);
          const endDate = new Date(this.appoint.endDate);
          const currentDate = new Date(time);

          // 禁用开始日期之前的日期
          if (currentDate < beginDate) return true;
          // 禁用结束日期之后的日期
          if (currentDate > endDate) return true;

          return false;
        }
      },
      // 表单校验
      rules: {},
      not_appoint:{
        open: false,
        userList:[],
        appointId:null,
      },
      score:{
        open:false,
        title:'',
        obj:{},
        puerperaScore:null,
        childrenScore:null,
        puerperaComment:null,
        childrenComment:null,
        scores:null,//展示的表格的分数
        comments:null,//展示的的备注
        activeName: 'puerpera',
        model:[],
        puerperaModel:[],
        childrenModel:[],
        teacher: JSON.parse(window.localStorage.getItem('user'))
      },
      project_merageArr: [],  //第一列进行合并操作时存放的数组变量
      project_meragePos: 0,  //上面的数组的下标值
      step_merageArr: [],  //第二列进行合并操作时存放的数组变量
      step_meragePos: 0, //上面的数组的下标值
    };
  },
  watch: {
    'score.activeName' : function (n,o){
      if (n === 'puerpera'){
        this.score.scores = this.score.puerperaScore;
        this.score.childrenComment = this.score.comments;
        this.score.comments = this.score.puerperaComment;
        this.score.model = copyArr(this.score.puerperaModel);
      }else{
        this.score.scores = this.score.childrenScore;
        this.score.puerperaComment = this.score.comments;
        this.score.comments = this.score.childrenComment;
        this.score.model = copyArr(this.score.childrenModel);
      }
      this.merage();
    },
    'score.scores': {
      handler(n,o){
        this.score.model[this.score.model.length - 1].step = arrSum(this.score.scores);
      },
      deep: true,//深度监听
    },
  },
  created() {
    this.getList();
    this.getAppointList();
    //读取json文件
    readJson('children').then(response => {
      this.score.childrenModel = response.data
    });
    readJson('puerpera').then(response => {
      this.score.puerperaModel = response.data
    });
  },
  mounted() {
    // 初始化时确保日期在范围内
    if (this.formAppointTime.appointDate) {
      const selectedDate = new Date(this.formAppointTime.appointDate)
      const beginDate = new Date(this.appoint.beginDate)
      const endDate = new Date(this.appoint.endDate)

      if (selectedDate < beginDate || selectedDate > endDate) {
        // 如果初始日期不在范围内，重置为开始日期
        this.formAppointTime.appointDate = this.appoint.beginDate
      }
    } else {
      // 如果没有初始值，设置为开始日期
      this.formAppointTime.appointDate = this.appoint.beginDate
    }
  },
  methods: {
    isEmptyArr,
    checkPermi,
    /** 查询实训预约时间段 */
    getAppointTimeList(){
      if (isEmptyStr(this.queryParams.appointId)){
        this.appointTimeList = [];
      }else{
        getAppoint(this.queryParams.appointId).then(response=>{
          this.appointTimeList = response.data.pvAppointTimeList;
        })
      }
    },
    /** 查询实训预约列表 */
    getAppointList() {
      listAppoint({pageSize:1000,pageNum:1}).then(response => {
        this.appointList = response.rows;
      });
    },
    handleDateChange(val) {
      this.formAppointTime.appointDate = val;
      // 可以在这里添加其他逻辑，如验证或触发其他操作
    },
    handleRadioChange(value) {
      console.log('选中的预约时间段ID:', value);
      // 可以在这里添加其他逻辑
      this.appointTimeId = value;
    },

    // 在 handleSupplementaryExamination 方法中添加日期验证
    handleSupplementaryExamination(row) {
      this.pvAppointRecordId = row.id
      getAppoint_record_time_list(row.appointId,row.id).then(response => {
        this.formAppointTime = response.data;
        this.appoint = response.data.appoint;
        this.pvAppointRecord =response.data.pvAppointRecord;
        console.log(this.pvAppointRecord)
        // 验证并修正日期范围
        this.validateAndCorrectDate();

        this.transformAppointTimeData(response.data);
        this.openSupplementaryExamination = true;
        this.title = "补考预约";
      });
    },

    validateAndCorrectDate() {
      if (!this.appoint.beginDate || !this.appoint.endDate) return;

      const beginDate = new Date(this.appoint.beginDate);
      const endDate = new Date(this.appoint.endDate);
      const selectedDate = this.formAppointTime.appointDate
        ? new Date(this.formAppointTime.appointDate)
        : null;

      // 如果没选日期或日期不在范围内，设置为开始日期
      if (!selectedDate || selectedDate < beginDate || selectedDate > endDate) {
        this.formAppointTime.appointDate = this.appoint.beginDate;
      }
    },
    /** 查询预约记录列表 */
    getList() {
      this.loading = true;
      if (null != this.daterangeAppointTime && '' != this.daterangeAppointTime) {
        this.queryParams.params["beginAppointDate"] = this.daterangeAppointTime[0];
        this.queryParams.params["endAppointDate"] = this.daterangeAppointTime[1];
      }
      listAppoint_record(this.queryParams).then(response => {
        this.appoint_recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSupplementaryExamination = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuId: null,
        appointId: null,
        appointTime: null,
        booking_time: null,
        doStatus: null,
        status: null,
        reservedOne: null,
        reservedTwo: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeAppointTime = [];
      this.queryParams.params = {};
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预约记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.form = {...row};
      this.open = true;
      this.title = "修改预约记录";
      getAppoint_record(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAppoint_record(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAppoint_record(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    updatePvAppointRecordForm(){

      const dataToSend = {
        pvAppointRecordId: this.pvAppointRecordId,
        appointDate: this.pvAppointRecord.appointDate,
        appointTimeId: this.appointTimeId
      };
      updateAppoint_buyuerecord(dataToSend).then(response => {
        this.openSupplementaryExamination = false;
        this.$modal.msgSuccess("修改成功");
        this.getList();
      })
    },
    /** 核准弹窗 */
    checkStatusCommand(command, row){
      var obj = {...row}
      obj.status = command
      updateAppoint_record(obj).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    /** 已履行 */
    checkDoStatusCommand(row){
      var obj = {...row}
      obj.doStatus = '1'
      updateAppoint_record(obj).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除预约记录编号为"' + ids + '"的数据项？').then(function () {
        return delAppoint_record(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 转换预约时间段数据结构
    transformAppointTimeData(data) {
      if (data && data.filteredList) {
        // 将原始数据转换为表格可编辑格式
        this.pvAppointTimeList = data.filteredList.map(item => {
          return {
            ...item,
            time: [item.startTime, item.endTime] // 将开始时间和结束时间组合成数组
          };
        });
      } else {
        this.pvAppointTimeList = [];
      }
    },

    // 添加预约时间段
    handleAddAppointTime() {
      this.pvAppointTimeList.push({
        id: null,
        appointId: this.formAppointTime?.appoint?.id || null,
        name: '',
        startTime: '',
        endTime: '',
        num: null,
        beginDate: null,
        endDate: null,
        time: [null, null] // 时间范围数组
      });
    },
    // 删除预约时间段
    handleDeleteAppointTime(index) {
      if (this.pvAppointTimeList.length <= 1) {
        this.$message.warning('至少保留一个时间段');
        return;
      }
      this.pvAppointTimeList.splice(index, 1);
    },

    // 保存预约时间段设置
    saveAppointTimeSettings() {
      // 将表格数据转换回原始格式
      const transformedData = this.pvAppointTimeList.map(item => {
        return {
          ...item,
          startTime: item.time && item.time[0] ? item.time[0] : '',
          endTime: item.time && item.time[1] ? item.time[1] : ''
        };
      });

      // 这里可以调用API保存数据
      console.log('保存的数据:', transformedData);
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('pv/appoint_record/export', {
        ...this.queryParams
      }, `appoint_record_${new Date().getTime()}.xlsx`)
    },
    //------------------------
    /** 未报名学员窗口 */
    handleNotAppoint(){
      this.not_appoint.open = true;
    },
    /** 查询未预约 */
    getNotAppointList(){
      get_not_appoint_list(this.not_appoint.appointId).then(response=>{
        this.not_appoint.userList = response.rows;
      })
    },
    //----------------------------------------------------
    /** 打开评分表 */
    openScore(row){
      this.$modal.loading('加载中……')
      getRecord_by_class_user(row.appoint.classId,row.stuId).then(response=>{
        this.score.title = row.student.nickName;
        this.score.obj = response.data;
        this.score.comments = response.data.puerperaComment;
        this.score.puerperaScore = parseObj(response.data.puerperaScore);
        this.score.childrenScore = parseObj(response.data.childrenScore);
        this.score.puerperaComment = response.data.puerperaComment;
        this.score.childrenComment = response.data.childrenComment;
        if (checkPermi(['pv:stu_record:edit:pregnant'])){
          this.score.activeName = 'puerpera';
          this.score.scores = this.score.puerperaScore;
          this.score.model = copyArr(this.score.puerperaModel);
        }else if(checkPermi(['pv:stu_record:edit:child'])){
          this.score.activeName = 'children';
          this.score.scores = this.score.childrenScore;
          this.score.model = copyArr(this.score.childrenModel);
        }
        this.merage();
        this.score.open = true;
        this.$modal.closeLoading();
      })
    },
    /** 修改 */
    recordUpdate(){
      if (this.score.activeName === 'puerpera'){
        this.score.puerperaComment = this.score.comments;
      }else{
        this.score.childrenComment = this.score.comments;
      }
      var body = {
        id: this.score.obj.id,
        puerperaScore: toJsonStr(this.score.puerperaScore),
        childrenScore: toJsonStr(this.score.childrenScore),
        puerperaComment: this.score.puerperaComment,
        childrenComment: this.score.childrenComment,
      }
      updateStu_record(body).then(response => {
        this.$message({message: '提交成功', type: 'success', offset: '300'});
        this.getList();
      });
    },
    resetScore(){
      this.score.title = '';
      this.score.obj = {};
      this.score.scores = [];
      this.score.activeName = 'puerpera';
      this.score.model = [];
    },
    /**--------------------------------------*/
    merageInit() { // 在下文的时候会用到，对数据进行初始化是很有必要的
      this.project_merageArr = [];
      this.project_meragePos = 0;
      this.step_merageArr = [];
      this.step_meragePos = 0;
    },
    // 合并多列专用
    merage() {
      this.merageInit(); // 前文的初始化数据函数
      for (let i = 0; i < this.score.model.length; i++) {
        if (i === 0) {
          // 第一行必须存在
          this.project_merageArr.push(1);
          this.project_meragePos = 0;
          this.step_merageArr.push(1);
          this.step_meragePos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同,eg：this.paragraph_meragePos 是 this.typeNameArr序号
          // 第一列
          if (this.score.model[i].project === this.score.model[i - 1].project) {
            this.project_merageArr[this.project_meragePos] += 1;
            this.project_merageArr.push(0);
          } else {
            this.project_merageArr.push(1);
            this.project_meragePos = i;
          }
          // 第二列
          if (this.score.model[i].step === this.score.model[i - 1].step && this.score.model[i].project === this.score.model[i - 1].project) {
            this.step_merageArr[this.step_meragePos] += 1;
            this.step_merageArr.push(0);
          } else {
            this.step_merageArr.push(1);
            this.step_meragePos = i;
          }
        }
      }
    },
    //合并列的方法
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      //合并最后一行 合计
      if (rowIndex === this.score.model.length - 1) {
        return [1, 4];
      }
      if (columnIndex === 0) {
        // 第一列的合并方法
        const row1 = this.project_merageArr[rowIndex];
        const col1 = row1 > 0 ? 1 : 0; // 如果被合并了row = 0; 则他这个列需要取消
        return {rowspan: row1, colspan: col1};
      } else if (columnIndex === 1) {
        // 第二列的合并方法
        const row2 = this.step_merageArr[rowIndex];
        const col2 = row2 > 0 ? 1 : 0; // 如果被合并了row = 0; 则他这个列需要取消
        return {rowspan: row2, colspan: col2};
      }
    }
  }
};
</script>
